package com.tgit.sso.core.util;

import java.io.IOException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
/**
 * md5加密工具
 * @author 范再军
 * 2018年9月18日
 */
public class Md5Util {

    public static String getMd5Str(String value) {
        try {
            MessageDigest messageDigest = MessageDigest.getInstance("MD5");
            messageDigest.update(value.getBytes("UTF-8"));
            byte[] byteArray = messageDigest.digest();
            StringBuffer md5StrBuff = new StringBuffer();
            for (int i = 0; i < byteArray.length; i++) {
                if (Integer.toHexString(0xFF & byteArray[i]).length() == 1) {
                    md5StrBuff.append("0").append(Integer.toHexString(0xFF & byteArray[i]));
                } else {
                    md5StrBuff.append(Integer.toHexString(0xFF & byteArray[i]));
                }
            }
            return md5StrBuff.toString();
        } catch (IOException e) {
            return value;
        } catch (NoSuchAlgorithmException e) {
            return value;
        }
    }

    public static long stringTolong(String str) {
        String[] myStr = {"a", "b", "c", "d", "e", "f"};
        long result = 0;
        int nr = 1;
        for (int i = str.length() - 1; i >= 0; i--) {
            String param = str.substring(i, i + 1);
            for (int j = 0; j < myStr.length; j++) {
                if (param.equalsIgnoreCase(myStr[j])) {
                    param = "1" + String.valueOf(j);
                }
            }
            result += Long.parseLong(param) * nr;
            nr *= 16;
        }
        return result;
    }

    public static long getUrlNum(String url, long appid) {
        long result = 0;
        try {
            //            if (url != null && url.indexOf("?") > -1) {
            //                url = url.substring(0, url.indexOf("?"));
            //            }
            String md5 = Md5Util.getMd5Str(url);
            String[] md5str = {md5.substring(0, 8), md5.substring(8, 16), md5.substring(16, 24), md5.substring(24, 32)};
            long[] long4 = {Md5Util.stringTolong(md5str[0]), Md5Util.stringTolong(md5str[1]), Md5Util.stringTolong(md5str[2]), Md5Util.stringTolong(md5str[3])};
            long chengji = long4[0] * long4[1] * long4[2] * long4[3];
            long chengji32 = (chengji << 32) >> 32;
            long roleid32 = appid << 32;
            result = roleid32 + chengji32;

        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }
    
    
    public static void main(String[] args) {
        System.out.println(getUrlNum("http://118.194.50.25:8080/browser/homepage/list",1063));
        System.out.println(getUrlNum("www.browser/business/approverview/init",1063));
    }
}
